package com.iknight.mgr.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.iknight.mgr.api.MenuService;
import com.iknight.mgr.mapper.MenuMapper;
import com.iknight.mgr.mapper.RoleMapper;
import com.iknight.mgr.model.MenuModel;
import com.iknight.mgr.model.RoleModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author Jeryzym
 */
@Service
public class MenuServiceImpl implements MenuService<MenuModel, String> {

    @Autowired
    private MenuMapper<MenuModel, String> menuMapper;

    @Autowired
    private RoleMapper<RoleModel, String> roleMapper;

    public void save(MenuModel record) {
        // TODO Auto-generated method stub
        if (menuMapper.selectOne(record.getMenu_id()) != null) {
            menuMapper.update(record);
        } else {
            menuMapper.insert(record);
            menuMapper.updateLeafFlag(record.getP_menu_id(), "0");//设置父级节点为非叶子节点
        }
    }

    /**
     * 增加事务支持，在删除菜单时，为避免垃圾数据产生，应级联删除菜单与角色关系
     */
    @Transactional
    public void delete(String pkey) {
        // TODO Auto-generated method stub
        //获取该节点的父级节点，判断父级节点是否有其他子节点
        MenuModel record = menuMapper.selectOne(pkey);
        roleMapper.releaseMenuFromRole(pkey);
        menuMapper.delete(pkey);

        Map map = new HashMap();
        map.put("p_menu_id", record.getP_menu_id());
        if (menuMapper.selectByCond(map) == null) {
            menuMapper.updateLeafFlag(record.getP_menu_id(), "1");
        }
    }

    public MenuModel selectOne(String pkey) {
        // TODO Auto-generated method stub
        return menuMapper.selectOne(pkey);
    }

    public PageInfo<MenuModel> selectPage(Map<String, Object> params, int pageStart, int pageSize) {
        // TODO Auto-generated method stub
        // return null;
        PageHelper.startPage(pageStart, pageSize, true);
        List<MenuModel> result = menuMapper.selectByCond(params);
        PageInfo<MenuModel> page = new PageInfo<MenuModel>(result);
        return page;
    }


    public List<MenuModel> selectAll() {
        // TODO Auto-generated method stub
        return menuMapper.selectAll();
    }


    public void changeMenuPid(String menu_id, String p_menu_id) {
        // TODO Auto-generated method stub
        menuMapper.changeMenuPid(menu_id, p_menu_id);
    }


    public List<MenuModel> getTreeNode(String nodeId) {
        return menuMapper.getTreeNode(nodeId);
    }

    public void updateLeafFlag(String menu_id, String isleaf) {
        menuMapper.updateLeafFlag(menu_id, isleaf);
    }

    @Override
    public String getNextShowOrder() {
        return menuMapper.getNextShowOrder();
    }
}
